<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="top-bar">
      <text class="top-title">我的工单列表</text>
    </view>

    <!-- 搜索栏（含历史记录触发） -->
    <view class="search-container">
      <view class="search-bar" @click.stop="showSearchHistory = true">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          placeholder="搜索工单标题/编号/地址" 
          v-model="searchKeyword" 
          placeholder-class="search-placeholder"
          @input="handleSearchInput"
          @focus="showSearchHistory = true"
          @blur="handleSearchBlur"
        />
        <!-- 清空关键词按钮 -->
        <text 
          class="clear-keyword" 
          v-if="searchKeyword.trim()" 
          @click.stop="clearSearch"
        >
          ×
        </text>
      </view>

      <!-- 新增：搜索历史记录区域（聚焦/有历史时显示） -->
      <view 
        class="search-history" 
        v-if="showSearchHistory && searchHistory.length > 0"
      >
        <!-- 历史标题栏 -->
        <view class="history-header">
          <text class="history-title">搜索历史</text>
          <!-- 清空全部按钮 -->
          <text class="clear-all" @click.stop="clearAllSearchHistory">
            清空全部
          </text>
        </view>

        <!-- 历史记录列表 -->
        <view class="history-list">
          <view 
            class="history-item" 
            v-for="(history, index) in searchHistory" 
            :key="index"
            @click.stop="handleHistoryClick(history)"
          >
            <text class="history-text">{{ history }}</text>
            <!-- 单个记录删除按钮 -->
            <text 
              class="delete-history" 
              @click.stop="deleteSearchHistory(index)"
            >
              ×
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 状态筛选栏 -->
    <view class="status-filter">
      <view 
        class="filter-item" 
        :class="{ active: currentStatus === null }" 
        @click="changeStatus(null)"
      >
        全部
      </view>
      <view 
        class="filter-item" 
        :class="{ active: currentStatus === 1 }" 
        @click="changeStatus(1)"
      >
        处理中
      </view>
      <view 
        class="filter-item" 
        :class="{ active: currentStatus === 2 }" 
        @click="changeStatus(2)"
      >
        已处理
      </view>
      <view 
        class="filter-item" 
        :class="{ active: currentStatus === 3 }" 
        @click="changeStatus(3)"
      >
        已结算
      </view>
    </view>

    <!-- 工单列表区域 -->
    <view class="workorder-list">
      <view 
        class="workorder-item" 
        v-for="(item, index) in filteredWorkorders" 
        :key="item.id" 
        @click="goDetail(item)"
      >
        <view class="item-header">
          <text class="item-title">{{ item.title }}</text>
          <view class="status-tag" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </view>
        </view>

        <view class="item-details">
          <view class="detail-row">
            <text class="detail-label">工单编号：</text>
            <text class="detail-value">{{ item.orderNo || item.id }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">创建时间：</text>
            <text class="detail-value">{{ formatTime(item.createTime) }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">处理时间：</text>
            <text class="detail-value">{{ item.handleTime ? formatTime(item.handleTime) : '未处理' }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">地点：</text>
            <text class="detail-value">{{ item.address || '未填写' }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">紧急程度：</text>
            <text class="detail-value" :class="getUrgencyClass(item.priorityType)">
              {{ getUrgencyText(item.priorityType) }}
            </text>
          </view>
        </view>

        <view class="action-buttons">
          <button 
            class="complete-btn" 
            v-if="item.status === 1" 
            @click.stop="completeHandle(item)"
          >
            标记完成
          </button>
        </view>
      </view>

      <!-- 空状态提示 -->
      <view class="empty-state" v-if="filteredWorkorders.length === 0 && !isLoading">
        <text class="empty-icon">📋</text>
        <text class="empty-text">
          {{ searchKeyword 
            ? '暂无匹配的工单' 
            : (currentStatus === null ? '暂无工单' : `暂无${getStatusText(currentStatus)}的工单`) 
          }}
        </text>
      </view>

      <!-- 加载中状态提示 -->
      <view class="loading-state" v-if="isLoading">
        <text class="loading-spinner">⏳</text>
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 底部导航组件 -->
    <bottom-nav :currentPath="currentPagePath"></bottom-nav>
  </view>
</template>

<script>
import bottomNav from '@/pages/components/bottom-nav/bottom-nav.vue';

export default {
  components: {
    bottomNav
  },
  data() {
    return {
      currentPagePath: '/pages/Employee/workorder/workorder',
      workorders: [],
      currentStatus: null,
      employeeId: null,
      isLoading: false,
      // 工单状态配置
      statusConfig: {
        1: { text: '处理中', class: 'status-processing' },
        2: { text: '已处理', class: 'status-handled' },
        3: { text: '已结算', class: 'status-settled' }
      },
      // 紧急程度配置
      urgencyConfig: {
        1: '普通',
        2: '紧急'
      },
      // 搜索相关：关键词 + 历史记录 + 历史显示状态
      searchKeyword: '',
      searchHistory: [], // 存储搜索历史（去重+时间倒序）
      showSearchHistory: false, // 控制历史记录区域显示/隐藏
      blurTimer: null // 用于延迟隐藏历史记录（避免点击时立即消失）
    };
  },
  onLoad() {
    // 1. 登录校验
    this.employeeId = uni.getStorageSync('employeeId');
    if (!this.employeeId) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => uni.navigateTo({ url: '/pages/login/login' }), 1000);
      return;
    }

    // 2. 读取本地存储的搜索历史
    this.loadSearchHistory();

    // 3. 加载工单数据
    this.loadWorkorders();
  },
  onShow() {
    // 监听工单状态更新事件
    uni.$on('workorderStatusUpdated', () => {
      this.loadWorkorders();
    });
    // 页面显示时刷新工单
    this.loadWorkorders();
  },
  onUnload() {
    // 移除事件监听 + 清除延迟定时器
    uni.$off('workorderStatusUpdated');
    clearTimeout(this.blurTimer);
  },
  computed: {
    // 筛选逻辑：有效工单 + 关键词搜索 + 状态筛选
    filteredWorkorders() {
      // 1. 排除状态为0（拒绝）的工单
      let validWorkorders = this.workorders.filter(item => item.status !== 0);
      
      // 2. 关键词模糊筛选（忽略大小写，匹配标题/编号/地址）
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase();
        validWorkorders = validWorkorders.filter(item => {
          const titleMatch = item.title?.toLowerCase().includes(keyword) || false;
          const orderNoMatch = (item.orderNo || item.id)?.toString().toLowerCase().includes(keyword) || false;
          const addressMatch = item.address?.toLowerCase().includes(keyword) || false;
          return titleMatch || orderNoMatch || addressMatch;
        });
      }

      // 3. 状态筛选
      if (this.currentStatus !== null) {
        validWorkorders = validWorkorders.filter(item => item.status === this.currentStatus);
      }

      return validWorkorders;
    }
  },
  methods: {
    // 状态筛选切换
    changeStatus(status) {
      this.currentStatus = status;
    },

    // 加载工单数据
    loadWorkorders() {
      this.isLoading = true;
      uni.request({
        url: 'http://localhost:6013/order-client/api/workOrderInfo/queryPageList',
        method: 'POST',
        header: { 'Content-Type': 'application/json' },
        data: {
          pageNum: 1,
          pageSize: 100,
          employeeId: this.employeeId
        },
        success: (res) => {
          this.isLoading = false;
          if (res.data?.code === 0 && res.data.data?.records) {
            this.workorders = res.data.data.records.map(item => ({
              ...item,
              orderNo: item.orderNo || `WO${item.id}`,
              title: item.title || '无标题工单',
              priorityType: item.priorityType ? Number(item.priorityType) : null
            }));
          } else {
            this.workorders = [];
          }
        },
        fail: () => {
          this.isLoading = false;
          uni.showToast({ title: '加载工单失败', icon: 'none' });
        }
      });
    },

    // 状态文本获取
    getStatusText(status) {
      return this.statusConfig[status]?.text || '未知状态';
    },

    // 状态标签样式获取
    getStatusClass(status) {
      return this.statusConfig[status]?.class || 'status-unknown';
    },

    // 紧急程度文本获取
    getUrgencyText(priorityType) {
      const type = priorityType ? Number(priorityType) : null;
      return this.urgencyConfig[type] || '未知';
    },

    // 紧急程度样式获取
    getUrgencyClass(priorityType) {
      const type = priorityType ? Number(priorityType) : null;
      if (type === 2) return 'urgency-urgent';
      if (type === 1) return 'urgency-ordinary';
      return 'urgency-unknown';
    },

    // 时间格式化（兼容iOS）
    formatTime(timeStr) {
      if (!timeStr) return '-';
      try {
        const cleanTime = timeStr.replace(/\.\d{3,}(Z|[+-]\d{2}:?\d{2})?$/, '').replace('T', ' ');
        const date = new Date(cleanTime);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      } catch (e) {
        return timeStr.substring(0, 16).replace('T', ' ') || '-';
      }
    },

    // 跳转到工单详情
    goDetail(item) {
      uni.navigateTo({ url: `/pages/Employee/workorder/detail?id=${item.id}` });
    },

    // 标记工单完成
    completeHandle(item) {
      uni.showModal({
        title: '标记完成',
        content: `确定“${item.title}”已处理完成吗？`,
        success: (res) => {
          if (res.confirm) {
            this.callCompleteApi(item.id);
          }
        }
      });
    },

    // 调用标记完成接口
    callCompleteApi(orderId) {
      uni.showLoading({ title: '提交中...' });
      uni.request({
        url: 'http://localhost:6013/order-client/api/employeeInfo/completeOrder',
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: {
          orderId: orderId,
          employeeId: this.employeeId
        },
        success: (res) => {
          uni.hideLoading();
          if (res.data?.code === 0) {
            uni.showToast({ title: '标记已处理成功', icon: 'success' });
            this.loadWorkorders();
          } else {
            uni.showToast({ title: res.data?.msg || '标记失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({ title: '网络错误，操作失败', icon: 'none' });
        }
      });
    },

    // ====================== 新增：搜索历史相关方法 ======================
    // 1. 从本地存储加载搜索历史
    loadSearchHistory() {
      const history = uni.getStorageSync('workorderSearchHistory') || [];
      this.searchHistory = history;
    },

    // 2. 保存搜索历史（去重+时间倒序+限制10条）
    saveSearchHistory(keyword) {
      const trimKeyword = keyword.trim();
      if (!trimKeyword) return; // 空关键词不保存

      // 去重：删除已有相同关键词
      this.searchHistory = this.searchHistory.filter(item => item !== trimKeyword);
      // 新增到最前面（时间倒序）
      this.searchHistory.unshift(trimKeyword);
      // 限制最多10条历史
      if (this.searchHistory.length > 10) {
        this.searchHistory.pop();
      }
      // 同步到本地存储
      uni.setStorageSync('workorderSearchHistory', this.searchHistory);
    },

    // 3. 搜索输入处理（实时筛选+保存历史）
    handleSearchInput() {
      // 防抖处理（300ms延迟，避免频繁筛选）
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        // 保存搜索历史（仅当关键词不为空时）
        if (this.searchKeyword.trim()) {
          this.saveSearchHistory(this.searchKeyword);
        }
      }, 300);
    },

    // 4. 清空搜索关键词
    clearSearch() {
      this.searchKeyword = '';
    },

    // 5. 点击搜索历史：回填关键词并筛选
    handleHistoryClick(history) {
      this.searchKeyword = history;
      this.showSearchHistory = false; // 回填后隐藏历史区域
    },

    // 6. 单个搜索历史删除
    deleteSearchHistory(index) {
      this.searchHistory.splice(index, 1);
      // 同步到本地存储
      uni.setStorageSync('workorderSearchHistory', this.searchHistory);
    },

    // 7. 清空全部搜索历史
    clearAllSearchHistory() {
      uni.showModal({
        title: '清空历史',
        content: '确定要删除所有搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = [];
            uni.removeStorageSync('workorderSearchHistory'); // 清除本地存储
          }
        }
      });
    },

    // 8. 搜索框失焦：延迟隐藏历史区域（避免点击历史时立即消失）
    handleSearchBlur() {
      this.blurTimer = setTimeout(() => {
        this.showSearchHistory = false;
      }, 200);
    }
  }
};
</script>

<style scoped>
/* 页面容器 */
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

/* 顶部导航栏 */
.top-bar {
  height: 100rpx;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

/* ====================== 新增：搜索区域样式 ====================== */
/* 搜索容器（包含搜索栏+历史记录） */
.search-container {
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  gap: 16rpx;
}

/* 搜索图标 */
.search-icon {
  font-size: 28rpx;
  color: #999;
}

/* 搜索输入框 */
.search-input {
  flex: 1;
  height: 56rpx;
  font-size: 26rpx;
  color: #333;
  border: none;
  outline: none;
  background: transparent;
}

/* 搜索占位符 */
.search-placeholder {
  color: #ccc;
  font-size: 26rpx;
}

/* 清空关键词按钮 */
.clear-keyword {
  font-size: 28rpx;
  color: #999;
  padding: 8rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
}
.clear-keyword:active {
  background-color: #eee;
}

/* 搜索历史区域 */
.search-history {
  padding: 0 24rpx 16rpx;
}

/* 历史标题栏（标题+清空全部） */
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-top: 1rpx solid #f0f0f0;
}

/* 历史标题 */
.history-title {
  font-size: 26rpx;
  color: #999;
}

/* 清空全部按钮 */
.clear-all {
  font-size: 24rpx;
  color: #5555ff;
}
.clear-all:active {
  color: #4444dd;
}

/* 历史记录列表 */
.history-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

/* 单个历史记录项 */
.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 16rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #333;
}

/* 历史记录文本 */
.history-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 单个历史删除按钮 */
.delete-history {
  font-size: 24rpx;
  color: #999;
  padding: 4rpx 8rpx;
  border-radius: 50%;
}
.delete-history:active {
  background-color: #eee;
  color: #666;
}

/* ====================== 原有样式 ====================== */
/* 状态筛选栏 */
.status-filter {
  display: flex;
  background-color: #fff;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #eee;
  overflow-x: auto;
}
.filter-item {
  flex: 0 0 auto;
  padding: 12rpx 24rpx;
  margin: 0 8rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f0f0f0;
}
.filter-item.active {
  background-color: #5555ff;
  color: #fff;
}

/* 工单列表区域 */
.workorder-list {
  padding: 16rpx;
}

/* 单个工单项 */
.workorder-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

/* 工单标题与状态标签 */
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16rpx;
}
.item-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  margin-right: 16rpx;
  word-break: break-all;
}
.status-tag {
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  white-space: nowrap;
}

/* 状态标签样式 */
.status-processing {
  background-color: #bbdefb;
  color: #1976d2;
}
.status-handled {
  background-color: #c8e6c9;
  color: #388e3c;
}
.status-settled {
  background-color: #e1bee7;
  color: #6a1b9a;
}
.status-unknown {
  background-color: #f5f5f5;
  color: #9e9e9e;
}

/* 工单详情区域 */
.item-details {
  border-top: 1rpx dashed #eee;
  padding-top: 16rpx;
  margin-bottom: 16rpx;
}
.detail-row {
  display: flex;
  margin-bottom: 10rpx;
  font-size: 26rpx;
}
.detail-label {
  color: #999;
  min-width: 140rpx;
}
.detail-value {
  color: #666;
  flex: 1;
}

/* 紧急程度样式 */
.urgency-ordinary {
  color: #666;
}
.urgency-urgent {
  color: #e53935;
  font-weight: bold;
}
.urgency-unknown {
  color: #999;
}

/* 操作按钮区域 */
.action-buttons {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
}
.complete-btn {
  padding: 8rpx 20rpx;
  font-size: 26rpx;
  border-radius: 6rpx;
  border: none;
  color: #fff;
  background-color: #4caf50;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  color: #999;
}
.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  color: #ddd;
}
.empty-text {
  font-size: 30rpx;
}

/* 加载中状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  color: #999;
}
.loading-spinner {
  font-size: 60rpx;
  margin-bottom: 20rpx;
  animation: spin 1.5s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
.loading-text {
  font-size: 30rpx;
}
</style>